// websocket.js
export function initWebSocket(that) {
  that.socketTask = uni.connectSocket({
    url: 'ws://localhost:8080/',
    success: () => {
      console.log('WebSocket连接成功');
      startHeartbeat();
    },
    fail: (error) => {
      console.error('WebSocket连接失败', error);
    }
  });

  that.socketTask.onOpen((res) => {
    console.log('WebSocket 已打开', res);
  });

  that.socketTask.onMessage((res) => {
    that.state = true;
    that.isOpenLoading = false;
    console.log('收到服务器内容：' + res.data);
  });

  that.socketTask.onError((error) => {
    console.error('WebSocket 错误', error);
  });

  that.socketTask.onClose((res) => {
    console.log('WebSocket 已关闭', res);
    that.state = false;
  });
}

export function sendHeartbeat(that) {
  if (that.socketTask && that.socketTask.readyState === 1) {
    that.socketTask.send({
      data: JSON.stringify({
        type: '数据'
      })
    });
  }
}

export function startHeartbeat(that) {
  setInterval(() => {
    sendHeartbeat(that);
  }, 5000); // 每5秒发送一次心跳
}

export function checkWebSocketConnection(that, interval) {
  setInterval(() => {
    console.log(`我正在每隔${interval/1000}s检查是否连接`);
    if (!that.state) {
      console.log('尝试重新连接WebSocket');
      // 尝试重新连接
      initWebSocket(that);
    }
  }, interval); // 每interval秒检查一次连接状态
}
